# Virginia .py
# 维吉尼亚加密算法
# -*- coding: utf-8 -*-
"""
Created on 2021

@author: Ximing
"""

alphabets = "abcdefghijklmnopqrstuvwxyz"
yourChoose = 1
# 定义加密函数
def encrypt(p, k):
	c = ""
	kpos = [] # 返回字符索引，例如:如果k='d'，那么kpos= 3
	for x in k:
		kpos.append(alphabets.find(x))
	i = 0
	for x in p:
		if i == len(kpos):
			i = 0
		pos = alphabets.find(x) + kpos[i] # 查找字符的编号或索引，并使用键执行移位
		# print(pos)
		if pos > 25:
			pos = pos-26
		c += alphabets[pos].capitalize()
		i +=1
	return c

# 定义解密函数
def decrypt(c, k):
	p = ""
	kpos = []
	for x in k:
		kpos.append(alphabets.find(x))
	i = 0
	for x in c:
		if i == len(kpos):
			i = 0
		pos = alphabets.find(x.lower()) - kpos[i]
		if pos < 0:
			pos = pos + 26
		p += alphabets[pos].lower()
		i +=1
	return p
try:
	while yourChoose == 1:
		print("==================维吉尼亚密码================\n"  
				"*注：文本消息应该只包含字符，键应该是一个字符单词 \n"  
				"==按 1 是加密一条消息 \n==按 2 是解密一条消息 \n==按 -1 退出")
		choose = input("+++选择: ")
		if choose == '1':
			yourChoose = 1
			p = input("输入明文消息: ")
			p = p.replace(" ", "")
			if p.isalpha():
				k = input("输入密钥: ")
				k = k.strip()
				if k.isalpha():
					c = encrypt(p, k)
					print("对应的密文为 ", c)

				else:
					print(k)
					print("输入有效密钥，密钥只有一个字符单词!")
			else:
				print("只允许英文!!")

		elif choose == '2':
			yourChoose = 1
			c = input("输入密文消息:")
			c = c.replace(" ", "")
			if c.isalpha():
				k = input("输入密钥: ")
				if not k.isalpha():
					print("输入有效密钥，密钥只有一个字符单词!")
				else:
					p = decrypt(c, k)
					print("对应的明文为: ", p)
			else:
				print("只允许英文!!")
		elif choose == '-1':
			break
		else:
			print("请输入一个有效的选择（1或2）")
except Exception as e:
	print(e)
	exit("请输入有效文本! ")
